<template>
  <div class="house-search">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <el-icon><Back /></el-icon>
        <span>返回</span>
      </div>
      <div class="title">房源搜索</div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input
        v-model="searchQuery"
        placeholder="输入城市、区域或小区名称..."
        class="search-input"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch" :loading="loading">
        搜索
      </el-button>
    </div>

    <!-- 搜索结果区域 -->
    <div class="search-results" v-if="searchResults.length > 0">
      <div v-for="house in searchResults" 
           :key="house.title" 
           class="house-card"
           @click="goToDetail(house)">
        <div class="house-card-content">
          <!-- 左侧房源信息 -->
          <div class="house-info">
            <h3 class="house-title">{{ house.title }}</h3>
            <p class="address">
              <el-icon><Location /></el-icon>
              {{ house.address }}
            </p>
            <div class="basic-info">
              <span class="area">{{ house.area }}㎡</span>
              <span class="orientation">{{ formatOrientation(house.orientation) }}</span>
            </div>
            <div class="facilities">
              <span v-for="facility in parseFacilities(house.facilities)" 
                    :key="facility"
                    class="facility-tag">
                {{ facility }}
              </span>
            </div>
            <p class="description">{{ house.description }}</p>
          </div>
          
          <!-- 右侧价格信息 -->
          <div class="price-info">
            <div class="price">¥{{ house.price }}/月</div>
            <div class="deposit">押金：¥{{ house.deposit }}</div>
            <div class="landlord">房东：{{ house.landlord }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 无结果提示 -->
    <el-empty 
      v-if="hasSearched && searchResults.length === 0"
      description="暂无符合条件的房源"
    />

    <!-- 分页 -->
    <div class="pagination" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search, Location, Back } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const searchQuery = ref('')
const searchResults = ref([])
const loading = ref(false)
const hasSearched = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 从路由参数获取搜索关键词
onMounted(() => {
  const searchText = route.query.text
  if (searchText) {
    searchQuery.value = searchText
    handleSearch()
  }
})

// 返回上一级
const goBack = () => {
  router.back()
}

// 跳转到详情页
const goToDetail = (house) => {
  router.push({
    path: '/house-detail',
    query: {
      id: house.id
    }
  })
}

// 处理搜索
const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  loading.value = true
  try {
    const params = {
      text: searchQuery.value,
      page: currentPage.value,
      page_size: pageSize.value
    }

    const response = await axios.get('http://127.0.0.1:8000/users/search/', { params })
    
    searchResults.value = response.data.results
    total.value = response.data.count
    hasSearched.value = true

  } catch (error) {
    console.error('搜索出错:', error)
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 格式化朝向
const formatOrientation = (orientation) => {
  const orientationMap = {
    'south': '朝南',
    'north': '朝北',
    'east': '朝东',
    'west': '朝西'
  }
  return orientationMap[orientation] || orientation
}

// 解析设施字符串为数组
const parseFacilities = (facilities) => {
  try {
    return JSON.parse(facilities.replace(/'/g, '"'))
  } catch (e) {
    return []
  }
}
</script>

<style scoped>
.house-search {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 顶部导航栏样式 */
.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.back-button {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #409eff;
  font-size: 14px;
}

.back-button:hover {
  opacity: 0.8;
}

.back-button .el-icon {
  margin-right: 5px;
}

.title {
  margin-left: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
}

.house-card {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.house-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.house-card-content {
  display: flex;
  justify-content: space-between;
}

.house-info {
  flex: 1;
  padding-right: 20px;
}

.house-title {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #303133;
}

.address {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
  margin: 8px 0;
}

.basic-info {
  margin: 10px 0;
}

.area, .orientation {
  display: inline-block;
  padding: 2px 8px;
  background-color: #f0f2f5;
  color: #606266;
  border-radius: 4px;
  margin-right: 10px;
  font-size: 14px;
}

.facilities {
  margin: 10px 0;
}

.facility-tag {
  display: inline-block;
  padding: 2px 8px;
  background-color: #ecf5ff;
  color: #409eff;
  border-radius: 4px;
  margin-right: 8px;
  margin-bottom: 8px;
  font-size: 12px;
}

.description {
  margin: 10px 0;
  color: #909399;
  font-size: 14px;
}

.price-info {
  text-align: right;
  min-width: 180px;
}

.price {
  font-size: 24px;
  color: #ff4d4f;
  font-weight: bold;
  margin-bottom: 10px;
}

.deposit, .landlord {
  color: #909399;
  font-size: 14px;
  margin-bottom: 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 